// 频道的数据操作

import { getUserChannels, getChannels } from '@/api/channels'

export default {
  namespaced: true,
  state: {
    // 我的频道数据
    channelList: [],
    // 所有的频道数据
    allChannelList: []
  },
  mutations: {
    setChannelList(state, payload) {
      state.channelList = payload
    },
    setAllChannelList(state, payload) {
      state.allChannelList = payload
    },
    addChannelList(state, payload) {
      state.channelList.push(payload)
    },
    delChannelList(state, payload) {
      state.channelList = state.channelList.filter(
        (item) => item.id !== payload.id
      )
    }
  },
  actions: {
    async actions_getUserChannels(context) {
      const {
        data: { channels }
      } = await getUserChannels()
      // console.log(channels)
      // this.channelList = channels
      context.commit('setChannelList', channels)
    },
    async actions_getAllChannels(context) {
      const {
        data: { channels }
      } = await getChannels()
      // console.log(channels)
      context.commit('setAllChannelList', channels)
    }
  },
  getters: {
    // 计算属性 ==> 需要计算出可选频道
    // 公式： 所有频道数据 - 我的频道数据 ==> 可选的
    optionsChannelList(state) {
      // 正确： 来遍历所有的频道数组，过滤出在我的频道里面没有的数据
      // return state.allChannelList.filter(item => {
      //   const res = state.channelList.some(channel => {
      //     return channel.id === item.id
      //   })
      //   // console.log(res)
      //
      //   if (res) {
      //     return false
      //   } else {
      //     return true
      //   }
      //* true ==> 表示已有该频道
      //* false ==> 未添加该频道
      // })
      // 代码简化结果
      return state.allChannelList.filter(
        (item) => !state.channelList.some((channel) => channel.id === item.id)
      )
    }
  }
}
